package com.xingji.caixia;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

import com.xingji.caixia.entitys.CardDao;
import com.xingji.caixia.entitys.UploadData;
import com.xingji.caixia.entitys.dataType;
import com.xingji.caixia.upload.Uploader;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 *
 * 服务主要用语处理刷卡记录上传...
 *
 */
public class MyService extends Service {

    ExecutorService executorService ;
    BlockingQueue<UploadData> queue;
    List<UploadData> list = null;

    public MyService() {
    }


    public class Mybinder extends Binder{

        public MyService getService(){
            return MyService.this;
        }
    }

    private Mybinder binder = new Mybinder();
    //test
    private final Random generator = new Random();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return binder;
//        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        executorService = Executors.newCachedThreadPool();
        queue = new LinkedBlockingDeque<UploadData>();
        startUpload();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    /**
     * 上传数据到服务器
     */
    private void startUpload(){
        try {
            list = CardDao.getCards(dataType.UNPLOAD);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (list.size()==0){
            this.sendBroadcast(new Intent(Constant.ZERO_READ));
            return;
        }
        for (final UploadData data:list){
            Log.e("ready start","data:"+data.toString());
            executorService.execute(new Uploader(queue,data,this));
        }
    }

    public void addUpload(UploadData data){
        //这里修改为只添加数据库 然后调用继续上传
        Log.e("data add",data.toString());
        this.sendBroadcast(new Intent(Constant.UNREAD));
//        executorService.execute(new Uploader(queue,data,this));
        startUpload();
    }

}
